define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, $rootScope, $sce, $state, $ionicHistory, $window, $ionicModal, $ionicNavBarDelegate, $ionicScrollDelegate, Http, GoPage, Auth, GoMap, GoWapAuth, $interval, $timeout, GoDialog,$ionicSlideBoxDelegate) {

		//引导页图片
		$rootScope.getwelcomes = function(callback) {
			Http.post({
					method: 'homepage.banner.get_guide'
				},
				function(result) {
					if(result.success) {
						//请求成功
						if(callback)
							callback(result.result);
					}
				}
			);
		};

		$rootScope.welcomes = new Array();
		$rootScope.welcomes.push({
			id: 0,
			url: './img/welcome/guid1.jpg',
			islast: false
		});
		$rootScope.welcomes.push({
			id: 1,
			url: './img/welcome/guid2.jpg',
			islast: false
		});
		$rootScope.welcomes.push({
			id: 2,
			url: './img/welcome/guid3.jpg',
			islast: true
		});
		$rootScope.getwelcomes(function(data) {
			if(data) {
				if(data.associate&&data.associate.length > 0) {
					$rootScope.welcomes = new Array();
					for(var i = 0; i < data.associate.length; i++) {
						if(i == data.associate.length - 1)//如果是最后一个，则显示“马上体验”按钮
							$rootScope.welcomes.push({
								id: data.associate[i].associate_id,
								url: data.associate[i].image_id,
								islast: true
							});
						else
							$rootScope.welcomes.push({
								id: data.associate[i].associate_id,
								url: data.associate[i].image_id,
								islast: false
							});
					}
					$ionicSlideBoxDelegate.$getByHandle('advs-handle').update(); //解决无法加载
					//$ionicSlideBoxDelegate.$getByHandle('advs-handle').loop(true); //循环
				}
				//图片开关
				if(data.image_search_open) {
					if($rootScope.init_search_open)
						$rootScope.init_search_open(data.image_search_open);
				}else{
					if($rootScope.init_search_open)
						$rootScope.init_search_open(false);
				}
			}
		});
		
		
		/************推送*************/
		$rootScope.getpushmessage = function(pushid, callback) {
			Http.post({
					method: 'info.message.getinfo',
					id: pushid
				},
				function(result) {
					if(result.success) {
						//请求成功
						if(callback)
							callback(result.result);
					}
				}
			);
		};
		$ionicModal.fromTemplateUrl('push-modal.html', {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			$rootScope.pushmodal = modal;
		});
		$rootScope.showpushMessage = function(pushid) {
			$rootScope.getpushmessage(pushid, function(data) {
				if(data.id != null) {
					$rootScope.pushTitleHtml = data.title;
					$rootScope.pushContentHtml = $sce.trustAsHtml(data.content);
					$rootScope.pushmodal.show();
				}
			});
		};
		$rootScope.hidepushMessage = function() {
			$rootScope.pushmodal.hide();
		};
		/************引导页*************/
		//新建地址
		$ionicModal.fromTemplateUrl('templates/modal/welcome.html', {
			scope: $scope
		}).then(function(modal) {
			$scope.startModal = modal;
			if(window.cordova && window.cordova.plugins) {//如果是app，才显示引导页面
				$scope.showstartApp();
			}
		});
		//离开主页面的时候一定要移除
		$scope.$on('$destroy', function() {
			$scope.startModal.remove();
			$scope.pushmodal.remove();
			$scope.shareguidmodal.remove();
		});
		$scope.showstartApp = function() {
			var isstart = Auth.getisrestart();
			//整体高度
			var all = $window.innerHeight;
			$scope.tartObj = { //搜索页面可视
				"height": all + "px"
			};
			if(isstart == undefined || isstart == '')
				$scope.startModal.show();
		};
		$scope.hidestartApp = function() {
			$scope.startModal.hide();
			Auth.saverestart();
		};
		/************引导页*************/
		/************模态窗口*************/
		$ionicModal.fromTemplateUrl('templates/modal/shareguid.html', {
			scope: $scope,
			animation: 'slide-in-up'
		}).then(function(modal) {
			$scope.shareguidmodal = modal;
		});
		//微信内置浏览器
		$scope.isWeiXin = function() {
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		}
		//qq内置浏览器
		$scope.isQQ = function() {
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.indexOf('qq') > -1) {
				return true;
			} else {
				return false;
			}
		}
		//点击分享
		$rootScope.closeGuidShare = function() {
			$scope.shareguidmodal.hide();
		};
		//点击分享
		$rootScope.openGuidShare = function() {
			//判断是否为app
			if(window.cordova && window.cordova.plugins) {
				return true;
			} else {
				if($scope.isWeiXin()) {
					$scope.shareguidmodal.show();
					return false;
				} else if($scope.isQQ()) {
					$scope.shareguidmodal.show();
					return false;
				} else {
					return true;
				}
			}
		};

		//1.loaded 创建
		//2.beforeEnter
		//3.enter 用户看见了界面
		//4.afterEnter 用户得到了界面焦点
		//5.beforeLeave 用户失去了界面焦点
		//6.leave 用户看不见了界面
		//7.afterLeave
		//8.unloaded 销毁
		$rootScope.noImg = "img/guilin/other/noImg.jpg"; //当没有图片时，显示这张图片
		$rootScope.$on('$ionicView.beforeEnter', function(scope, status) {
			var statename = $state.current.name;
			//tabs中存在的主页面不需要隐藏，hidetabs=false
			if(statename === 'tab.home' ||
				statename === 'tab.classes' ||
				statename === 'tab.findus' ||
				statename === 'tab.cart' ||
				statename === 'tab.center') {
				$rootScope.hideTabs = false;
			} else {
				$rootScope.hideTabs = true;
			}
			Auth.get_issue_type_class();
		});
		$rootScope.$on('$ionicView.afterEnter', function(scope, status) {
			$rootScope.goshowhomes();
			solutionView();
			//判断是否ios
			if(window.cordova && window.cordova.plugins) {
				if(ionic.Platform.isIOS()) {
					$scope.isIOSApp = true;
				} else {
					$scope.isIOSApp =  false;
				}
			} else {
				$scope.isIOSApp =  false;
			}
		});
		
		//监听路由事件 
		$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
			GoWapAuth.execisoff(true); //默认关闭
		});
		//打开客服
		$rootScope.opencustemOK = function() {
			GoPage.go_tolive800();
		};
		//回到顶部
		$rootScope.myScrollTop = function() {
			$ionicScrollDelegate.scrollTop();
		};
		//请求定位
		$scope.get_location = function(params, callback) {
			Http.post({
					method: 'position.getarea.location',
					longitude: params.longitude,
					latitude: params.latitude
				},
				function(result) {
					if(result.success) {
						//请求成功
						if(callback)
							callback(result.result);
					}
				}
			);
		};
		//定位获取
		$rootScope.init_tablocaltion = function() {
			//初始化定位地址
			GoMap.get_currentlocation(function(point) {
				//获取到百度坐标
				var params = {
					longitude: point.lng,
					latitude: point.lat
				};
				//内存保存数据
				GoMap.clear_homelocaltion();
				//设置保存
				GoMap.set_homelocaltion({
					longitude: point.lng,
					latitude: point.lat
				});
				//请求转换
				$scope.get_location(params, function(data) {
					if(data.session != undefined) {
						Auth.save_session(data.session);
					}
					if($rootScope.init_localtion)
						$rootScope.init_localtion(data.district_id);
				})
			});
		};
		//定位获取
		$rootScope.init_tabs = function() {
			if(!GoWapAuth.isWeiXin()) {
				//执行定位操作
				$rootScope.init_tablocaltion();
			}
		}
		$rootScope.init_tabs();

		/**********************红包通知*********************/
		//获取红包
		function getRedBag(){
			var isLogin = Auth.check_loginInfo();//不登录，不显示红包通知
			if(!isLogin) {
				document.getElementById("commonRedBagGif").style.display = "none";
				return;
			}
			Http.postHide({
				method: 'member.redbag_cpon.getlist'
			}, function(data) {
//				console.log(data);
				if(data.result && data.result.redbag_list) {
					document.getElementById("commonRedBagGif").style.display = "block";
					$scope.redBagIndex = 0; //红包的下标，即redbag_list的下标
					$scope.redBagData = data.result.redbag_list;
				} else {
					document.getElementById("commonRedBagGif").style.display = "none";
				}
			})
		}
		//更新红包，让红包只显示一次。红包页面一显示，就调用该接口
		function updateRedBag(log_id) {
			Http.postHide({
				method: 'member.redbag.update',
				log_id: log_id
			}, function(data) {
				//				console.log(data);
			})
		}
		//开红包。点击”开“调用该接口
		function openRedBag(log_id) {
			Http.postHide({
				method: 'member.redbag.openredbag',
				log_id: log_id
			}, function(data) {
				if(data.success) {
					GoDialog.toast("第" + ($scope.redBagIndex + 1) + "个红包领取成功！");
				}
			})
		}

		//定时器。显示红包，就清除定时器，领完红包再启动
		var redBagTimer;
		function redBagTimerFun() {
			redBagTimer = $interval(function() { //定时器
				getRedBag()
			},30000)
		}
		redBagTimerFun();

		$ionicModal.fromTemplateUrl("templates/modal/redBagCommon.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modalRedbag = modal;
		});
		//打开红包modal
		$rootScope.showRedBagCommonModal = function($event) {
			if($event) $event.stopPropagation(); //阻止事件冒泡
			$scope.redBagDataOne = $scope.redBagData[$scope.redBagIndex]; //红包详情
			if(!$scope.modalRedbag._isShown) {
				$scope.modalRedbag.show();
				document.getElementById("commonRedBagGif").style.display = "none";
			}
			if($scope.redBagIndex==0){//取消一次即可
				$interval.cancel(redBagTimer);//取消定时器
			}
			updateRedBag($scope.redBagDataOne.log_id);
		}
		//关闭红包modal。关闭时，如果有红包，会连续显示，不用每次都点击gif图片
		$rootScope.closeRedBagCommonModal = function() {
			$scope.isShowRedBagOpen = false;
			$scope.redBagIndex++;
			if($scope.redBagData.length > $scope.redBagIndex) { //如果还有红包，则继续显示
				$rootScope.showRedBagCommonModal(); //再次显示红包
			} else {
				redBagTimerFun();
				$scope.modalRedbag.hide();
				document.getElementById("commonRedBagGif").style.display = "none";
			}
		}
		//开红包
		$rootScope.openRedBagCommon = function() {
			$scope.isShowRedBagOpen = true; //显示“开”
			openRedBag($scope.redBagDataOne.log_id);
		}
		/**********************红包通知*********************/
		
		$rootScope.goshowhomes = function() {
			//判断最顶部的页面
			var statename = $state.current.name;
			var views = $ionicHistory.viewHistory().views;
			var items = new Array
			for(var view in views) {
				items.push(views[view]);
			}
			var view = items[0];
			if(view.stateName == 'tab.home' ||
				view.stateName == 'tab.classes' ||
				view.stateName == 'tab.findus' ||
				view.stateName == 'tab.cart' ||
				view.stateName == 'tab.center') {
				$rootScope.isshowhomes = false;
			} else {
				if(statename == view.stateName) {
					$rootScope.isshowhomes = true;
				} else {
					$rootScope.isshowhomes = false;
				}
			}
		}
		$rootScope.gobackhomes = function() {
			//GoPage.go_tabPage("home");
			window.location.href=HTTP_API;
			//$timeout(function() {
			//	window.location.reload();
			//}, 300);
		}
		
		/*****************显示一半页面的解决方案*****************/
		function solutionView(){
			var panes = document.getElementsByClassName("pane");
			for (var i=0;i<panes.length;i++) {
				var transform = panes[i].style.transform;
				if(transform=="translate3d(-33%, 0px, 0px)"){
					panes[i].style.transform = "translate3d(-100%, 0px, 0px)";
				}
			}
		}

	}

	controller.$inject = ['$scope', '$rootScope', '$sce', '$state', '$ionicHistory', '$window', '$ionicModal', '$ionicNavBarDelegate', '$ionicScrollDelegate', 'Http', 'GoPage', 'Auth', 'GoMap', 'GoWapAuth', '$interval', '$timeout', 'GoDialog','$ionicSlideBoxDelegate'];

	return app.registerController("tabsctrl", controller);
});